import { defineStore } from "pinia";
import { login as loginApi, getInfo, setInfoApi } from "@/api/user";
import { tip } from "@/utils";
interface UserState {
  user_id: number | null;
  isLogin: boolean;
  token: string | null;
  userInfo: any;
  referee:number;		//本次打开的推荐人id
}
export const userStore = defineStore("user", {
  state: (): UserState => ({
    user_id: null,
    isLogin: false,
    token: uni.getStorageSync("token") || null,
    userInfo: {},
	referee:0,	
  }),
  getters: {
    getUserInfo(state): Omit<UserState, "isLogin" | "token"> {
      return {
        user_id: state.user_id,
        userInfo: state.userInfo,
		referee:state.referee,
      };
    },
  },
  actions: {
    async login() {
      try {
		  let _self = this
		  uni.login({
		    provider: 'weixin', //使用微信登录
		    success: function (loginRes) {
		  		let code = loginRes.code
				let param = {
					code:code,
					user_info:{},
					referee_id:_self.referee
				}
				console.log(param)
		  		loginApi(param).then((res:any)=>{
					console.log(res)
		  			_self.token = res.token
		  			uni.setStorageSync('token',res.token)
					_self.fetchUserInfo();
		  		})
		    },
		    fail:(res)=>{
				console.log(res)
		    }
		  })
        return true;
      } catch (error: any) {
        this.isLogin = false;
        tip("登录失败:" + error);
        return false;
      }
    },
    async fetchUserInfo() {
		try {
			var token = this.token;
			console.log("token:",token)
			if(token){
				const res: any = await getInfo();
				this.userInfo = res.userInfo;
				this.user_id = res.userInfo.user_id;
				this.isLogin = true;
			}
			else{
				this.login();
			}
		} catch (error) {
			console.error("获取用户信息失败:", error);
			this.logout();
		}
    },
    logout() {
      this.user_id = null;
      this.userInfo = {};
      this.isLogin = false;
      this.token = null;
      uni.removeStorageSync("token");
    },
	setReferee(referee:number){
		console.log("referee",referee)
		this.referee = referee
	},
    async setInfo(info: any) {
      try {
        await setInfoApi(info);
        this.userInfo = {
          ...this.userInfo,
          ...info,
        };
      } catch (error: any) {
        tip("更新失败" + error);
      }
      return this.userInfo;
    },
  },
});
